package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RefreshScope
@Getter
@Setter
public class InitSeckillProductJob implements SimpleJob {
    @Value("${jobCron.userCache}")
    private String cron;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println("分片参数:"+shardingContext.getShardingParameter());
        dowork(shardingContext.getShardingParameter());
    }
    private void dowork(String time) {
        //存入新的数据之前,把之前的数据删除
        redisTemplate.delete(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time));
        redisTemplate.delete(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time));
        //存入redis中
        //创建key
        String listkey= JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time);
        //远程调用秒杀服务
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.querySeckillProduct(Integer.parseInt(time));
        if(result!=null&&!result.hasError()){
            List<SeckillProductVo> list = result.getData();
            //如果有值就存到redis中
            if(list!=null&list.size()>0){
                //list<SeckillProductVO>放到redis中
                for (SeckillProductVo seckillProductVo : list) {
                    //因为id是long类型所以要转换成String类型,因为存进redis到时候页面直接拿取所以要转换成JSON数据格式
                    redisTemplate.opsForHash().put(listkey,seckillProductVo.getId()+"", JSON.toJSONString(seckillProductVo));
                    //把库存数存到redis中
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time+""),seckillProductVo.getId()+"",seckillProductVo.getStockCount()+"");
                }
                System.out.println("数据初始化"+time);
            }
        }
    }
}
